<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>网抑郁音乐</title>
    <!-- 1. bootstrap.css/bootstrap.min.css -->
    <link rel="stylesheet" href="/dev/plugins/bootstrap/css/bootstrap.css">
    <style>
        @import url(../css/index.css);
        @import url(../css/nav.css);

    </style>
</head>
<body>
<nav class="navbar navbar-inverse" role="navigation">
    <div class="collapse navbar-collapse" id="example-navbar-collapse">
        <!-- 导航栏 -->
        <ul class="nav navbar-nav">
            <li class="active"><a href="index.html">首页</a></li>
            <li><a href="/dev/view/topChart/rank.html">排行榜</a></li>
            <li><a href="/dev/view/playList/playlist.html">歌单</a></li>
        </ul>

        <!-- 登录按钮 -->
        <ul class="nav navbar-nav navbar-right" id="loginButton">
            <li><a href="#" data-toggle="modal" data-target="#myModal">登录</a></li>
            <!-- 初始隐藏头像 -->
            <li><img id="nav_img" src="../img/1.png" style="display: none;"></li>
        </ul>

        <!-- 搜索框 -->
        <form class="navbar-form navbar-right" id="searchForm">
            <div class="form-group">
                <input type="text" class="form-control" id="searchInput" placeholder="搜索音乐">
            </div>
            <button type="submit" class="btn btn-default" onclick="gotoSearch()">搜索</button>
        </form>

    </div>
    </div>

    <!-- 模态框（Modal）-begin -->
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4 class="modal-title" id="myModalLabel">用户登录入口
                        
                    </h4>
                </div>
                <div class="modal-body">
                    <!-- 登录表单   -begin -->
                    <form class="form-horizontal" role="form">
                        <!-- 添加 has-feedback 类 -->
                        <div class="form-group has-feedback">
                            <label for="email" class="col-sm-2 control-label">邮箱</label>
                            <div class="col-md-8">
                                <input type="text" class="form-control" id="email" placeholder="请输入邮箱">
                                <span class="form-control-feedback glyphicon glyphicon-envelope"></span>
                                <span class="text-danger" id="email_span" style="display: none">sorry,email is not found!</span>
                            </div>
                            <div class="col-md-2" style="margin-left: -20px;">
                                <button type="button" class="btn btn-success" onclick="send_code()" id="sendCodeBtn">发送验证码</button>
                            </div>
                        </div>
                        <!-- 添加 has-feedback 类 -->
                        <div class="form-group has-feedback">
                            <label for="code" class="col-sm-2 control-label">验证码</label>
                            <div class="col-md-8">
                                <input type="text" class="form-control" id="code" placeholder="请输入验证码">
                                <span class="form-control-feedback glyphicon glyphicon-phone"></span>
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-sm-offset-2 col-sm-10">
                                <div class="checkbox">
                                    <label>
                                        <input type="checkbox">请记住我
                                    </label>
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-sm-offset-2 col-sm-10">
                                <button type="button" class="btn btn-default" onclick="login()">登录</button>
                            </div>
                        </div>
                    </form>
                    <!-- 登录表单 -end -->
                </div>
                <div class="modal-footer">
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal -->
    </div>
    <!-- 模态框（Modal）- end -->
</nav>

<div id="musicCarousel" class="carousel slide" data-ride="carousel" data-interval="3000">
    <!-- 指示器 -->
    <ol class="carousel-indicators">
        <li data-target="#musicCarousel" data-slide-to="0" class="active"></li>
        <li data-target="#musicCarousel" data-slide-to="1"></li>
        <li data-target="#musicCarousel" data-slide-to="2"></li>
    </ol>

    <!-- 轮播内容 -->
    <div class="carousel-inner">
        <div class="item active">
            <img src="/dev/img/lunbo1.jpg" alt="热门专辑">
            <div class="carousel-caption">
                <h3>本周热门单曲</h3>
                <p>最新上榜音乐抢先体验</p>
            </div>
        </div>
        <div class="item">
            <img src="/dev/img/lunbo2.jpg" alt="热门专辑">
            <div class="carousel-caption">
                <h3>精选歌单推荐</h3>
                <p>百万用户收藏的经典合集</p>
            </div>
        </div>
        <div class="item">
            <img src="/dev/img/lunbo3.jpg" alt="热门专辑">
            <div class="carousel-caption">
                <h3>限时会员福利</h3>
                <p>开通会员享专属音质</p>
            </div>
        </div>
        <div class="item">
            <img src="/dev/img/lunbo4.jpg" alt="活动促销">
            <div class="carousel-caption">
                <h3>限时会员福利</h3>
                <p>开通会员享专属音质</p>
            </div>
        </div>
    </div>

    <!-- 控制按钮 -->
    <a class="left carousel-control" href="#musicCarousel" role="button" data-slide="prev">
        <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
        <span class="sr-only">Previous</span>
    </a>
    <a class="right carousel-control" href="#musicCarousel" role="button" data-slide="next">
        <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
        <span class="sr-only">Next</span>
    </a>
</div>

<!-- 热门音乐推荐和侧边栏 -->
<div class="container mt-4">
    <div class="row">
        <!-- 热门音乐推荐 -->
        <div class="col-md-9">
            <h3 style="color: #3498db;">热门音乐推荐</h3>
            <div class="row">
                <!-- 第一排 -->
                <div class="col-md-4 col-sm-6">
                    <div class="thumbnail">
                        <a href="/dev/view/songDetail/player.html?songId=1" class="thumbnail-link">
                            <img src="/dev/img/告白.jpg" alt="热门音乐1" class="img-responsive">
                        </a>
                        <div class="caption">
                            <h4>告白气球</h4>
                            <p>周杰伦</p>
                        </div>
                    </div>
                </div>
                <div class="col-md-4 col-sm-6">
                    <div class="thumbnail">
                        <a href="/dev/view/songDetail/player.html?songId=2" class="thumbnail-link">
                            <img src="/dev/img/修炼爱情.jpg" alt="热门音乐1" class="img-responsive">
                        </a>
                        <div class="caption">
                            <h4>修炼爱情</h4>
                            <p>林俊杰</p>
                        </div>
                    </div>
                </div>
                <div class="col-md-4 col-sm-6">
                    <div class="thumbnail">
                        <a href="/dev/view/songDetail/player.html?songId=3" class="thumbnail-link">
                            <img src="/dev/img/光年.jpg" alt="热门音乐1" class="img-responsive">
                        </a>
                        <div class="caption">
                            <h4>光年之外</h4>
                            <p>邓紫棋</p>
                        </div>
                    </div>
                </div>
                <!-- 第二排 -->
                <div class="col-md-4 col-sm-6">
                    <div class="thumbnail">
                        <a href="/dev/view/songDetail/player.html?songId=4" class="thumbnail-link">
                            <img src="/dev/img/懂了.jpg" alt="热门音乐1" class="img-responsive">
                        </a>
                        <div class="caption">
                            <h4>开始懂了</h4>
                            <p>孙燕姿</p>
                        </div>
                    </div>
                </div>
                <div class="col-md-4 col-sm-6">
                    <div class="thumbnail">
                        <a href="/dev/view/songDetail/player.html?songId=5" class="thumbnail-link">
                            <img src="/dev/img/K歌.jpg" alt="热门音乐1" class="img-responsive">
                        </a>
                        <div class="caption">
                            <h4>K歌之王</h4>
                            <p>陈奕迅</p>
                        </div>
                    </div>
                </div>
                <div class="col-md-4 col-sm-6">
                    <div class="thumbnail">
                        <a href="/dev/view/songDetail/player.html?songId=6" class="thumbnail-link">
                            <img src="/dev/img/匆匆.jpg" alt="热门音乐1" class="img-responsive">
                        </a>
                        <div class="caption">
                            <h4>匆匆那年</h4>
                            <p>王菲</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-md-3 sidebar">
            <!-- 用户头像 -->
            <div class="user-avatar" style="display: none;">
                <img src="../img/1.png" alt="用户头像" class="img-circle">
            </div>

            <!-- 用户信息 -->
            <h4 style="color: #3498db;">个人信息</h4>
            <p style="color: #3498db;" id="username">用户名: [用户名]</p>
            <p style="color: #3498db;" id="userLevel">等级: [等级]</p>
            <p style="color: #3498db;" id="userPoints">积分: [积分]</p>
        </div>
    </div>
</div>
<div class="modal fade" id="updateUsernameModal" tabindex="-1" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title">修改默认用户名</h4>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <label>新用户名</label>
                    <input type="text" id="newUsername" class="form-control">
                    <span id="usernameError" class="text-danger" style="display:none">用户名已存在</span>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" onclick="submitNewUsername()">提交</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

<!-- 调试验证码弹窗 -->
<div class="modal fade" id="debugCodeModal" tabindex="-1" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-warning">
                <h4 class="modal-title">DEBUG 模式 - 验证码</h4>
            </div>
            <div class="modal-body">
                <p>验证码：<strong id="debugCodeValue"></strong></p>
                <small class="text-muted">（此弹窗仅用于开发调试，生产环境应移除）</small>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>


<script src="../js/search.js"> </script>
<!-- jquery.min.js文件 - jquery本身是js的框架. bootstrap依赖于jquery框架 -->
<script src="../plugins/jquery/jquery.min.js"></script>
<!-- bootstrap.js/bootstrap.min.js -->
<script src="../plugins/bootstrap/js/bootstrap.js"></script>
<script>
    // ================== 全局变量 ================== //
    let resendTimer = null; // 验证码重发计时器

    // ================== 初始化事件监听 ================== //
    $(document).ready(function() {
        // 登录模态框显示时初始化
        $('#myModal').on('show.bs.modal', function() {
            $('#email, #code').val('');
            $('.text-danger').hide();
        });

        // 用户名修改模态框隐藏时清理
        $('#updateUsernameModal').on('hidden.bs.modal', function() {
            $('#newUsername').val('');
            $('#usernameError').hide();
        });
    });

    // ================== 登录功能 ================== //
    function login() {
        const email = $('#email').val().trim();
        const code = $('#code').val().trim();

        if (!validateEmail(email)) {
            showAlert('邮箱格式错误', 'email_span');
            return;
        }

        $.ajax({
            url: '/dev/user',
            type: 'POST',
            data: { email, code },
            success: function(res) {
                if (res.code === "200") {
                    handleLoginSuccess(res.data);
                } else {
                    showAlert(res.msg || '登录失败', 'code_span');
                }
            },
            error: handleApiError
        });
    }

    // ================== 处理登录成功 ================== //
    function handleLoginSuccess(data) {
        localStorage.setItem('token', data.token);
        const $loginModal = $('#myModal');

        // 关闭登录模态框
        $loginModal.modal('hide');

        // 监听模态框完全关闭事件
        $loginModal.on('hidden.bs.modal', function() {
            $(this).off('hidden.bs.modal'); // 移除事件监听

            if (data.needUpdateUsername) {
                showUsernameUpdateModal();
            } else {
                updateUIAfterLogin();
            }
        });
    }

    // ================== 显示用户名修改模态框 ================== //
    function showUsernameUpdateModal() {
        $('#updateUsernameModal').modal('show');

        // 确保模态框渲染完成后设置焦点
        setTimeout(() => {
            $('#newUsername').trigger('focus');
        }, 100);
    }

    // ================== 更新登录后UI ================== //
    function updateUIAfterLogin() {
        // 转移焦点到页面主内容
        $('main').attr('tabindex', '-1').trigger('focus');

        // 更新用户信息显示
        updateUserInfo();

        // 隐藏登录按钮
        $('#loginButton').fadeOut(300);
    }

    // ================== 发送验证码 ================== //
    function send_code() {
        const email = $('#email').val().trim();
        const $btn = $('#sendCodeBtn');

        if (!validateEmail(email)) {
            showAlert('请输入有效邮箱地址', 'email_span');
            return;
        }

        $btn.prop('disabled', true);

        $.ajax({
            url: `/dev/user?email=${email}`,
            success: function(res) {
                if (res.code === "200") {
                    // 显示调试信息（开发环境）
                    if (isDevelopment()) {
                        $('#debugCodeValue').text(res.data);
                        $('#debugCodeModal').modal('show');
                    }

                    startResendTimer($btn);
                    showToast('验证码已发送');
                } else {
                    showAlert(res.message || '发送失败', 'email_span');
                }
            },
            error: handleApiError,
            complete: () => $btn.prop('disabled', false)
        });
    }

    // ================== 提交新用户名 ================== //
    function submitNewUsername() {
        const newUsername = $('#newUsername').val().trim();
        const token = localStorage.getItem('token');

        if (!newUsername) {
            showAlert('用户名不能为空', 'usernameError');
            return;
        }

        $.ajax({
            url: '/dev/user/updateUsername',
            type: 'POST',
            headers: { 'Authorization': token },
            data: { newUsername },
            success: function(res) {
                if (res.code === "200") {
                    $('#updateUsernameModal').modal('hide');
                    updateUserInfo();
                    showToast('用户名更新成功');
                } else {
                    showAlert(res.msg || '更新失败', 'usernameError');
                }
            },
            error: handleApiError
        });
    }

    // ================== 辅助函数 ================== //
    // 邮箱格式验证
    function validateEmail(email) {
        return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
    }

    // 启动重发计时器
    function startResendTimer($btn) {
        clearInterval(resendTimer);
        let seconds = 60;

        resendTimer = setInterval(() => {
            $btn.text(`重新发送(${seconds}s)`);
            if (seconds-- <= 0) {
                clearInterval(resendTimer);
                $btn.text('发送验证码').prop('disabled', false);
            }
        }, 1000);
    }

    // 显示浮动提示
    function showToast(message) {
        const $toast = $(`<div class="toast">${message}</div>`);
        $('body').append($toast);
        setTimeout(() => $toast.remove(), 2000);
    }

    // 统一错误处理
    function handleApiError(xhr) {
        const message = xhr.responseJSON?.msg || '服务不可用，请稍后重试';
        showToast(`${message} (${xhr.status})`);
    }

    // 环境检测
    function isDevelopment() {
        return window.location.hostname === 'localhost' ||
            window.location.hostname === '127.0.0.1';
    }

    // 更新用户信息
    function updateUserInfo() {
        const token = localStorage.getItem('token');
        if (!token) return;

        $.ajax({
            url: '/dev/user/info',
            headers: { 'Authorization': token },
            success: function(res) {
                if (res.code === "200") {
                    // 更新侧边栏信息
                    $('#username').text(`用户: ${res.data.username}`).show();
                    $('#userLevel').text(`等级: ${res.data.userLevel || '未设置'}`).show();
                    $('#userPoints').text(`积分: ${res.data.points || 0}`).show();
                    $('#pleaseLogin').hide();
                    // 更新头像显示
                    $('.user-avatar').show()
                        .find('img').attr('src', res.data.avatar || '../img/1.png');

                    // 更新导航栏头像
                    $('#nav_img').show().attr('src', res.data.avatar || '../img/1.png');
                }
            },
            error: handleApiError
        });
    }

    function gotoSearch() {
        const keyword = $('#searchInput').val().trim();
        window.location.href = `/dev/view/search/search.html?keyword=${encodeURIComponent(keyword)}`;
    }
</script>
</body>
</html>